<?php

function blog_get_categories($parent_id, $current_path, $level, &$category, &$category_children, $ancestors, &$categories_flat) {
	global $db, $site, $path;
	
	$categories = $db->fetchAll("SELECT *, 'blog' AS context FROM blog_categories WHERE site_id=? AND parent_id=? ORDER BY sort", array($site['id'], $parent_id));
	for($i=0;$i<count($categories);$i++) {
		foreach($ancestors as $ancestor) {
			$category_children[$ancestor][] = $categories[$i]['id'];
		}
		$categories[$i]['full_path'] = $current_path . $categories[$i]['path'] . '/';
		$categories_flat[$categories[$i]['id']] = $categories[$i];
		if (isset($path[$level]) and $path[$level] == $categories[$i]['path']) {
			$categories[$i]['ancestor'] = 1;
			if (!isset($path[$level+1])) {
				// this is the last element in the path, so it's also active
				$categories[$i]['active'] = 1;
			}
			$category = $categories[$i];
		}
		$categories[$i]['children'] = blog_get_categories($categories[$i]['id'], $categories[$i]['full_path'], $level+1, $category, &$category_children, array_merge($ancestors, array($categories[$i]['id'])), &$categories_flat);
		$categories[$i]['post_count'] = $db->fetchOne("SELECT COUNT(*) FROM blog_posts WHERE site_id=? AND active=1 AND  category_id IN (" . join(',', array_merge(array($categories[$i]['id']), (isset($category_children[$categories[$i]['id']]) ? $category_children[$categories[$i]['id']] : array()))) . ")", $site['id']);
	}
	return $categories;
}
